package base_project.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.xdclass.base_project.FastjsonApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import java.util.Set;

/**
 * @author sqz
 * @Description: fastjson对json字符串JSONObject和JSONArray互相转换操作示例
 * @date 2019/3/20 10:58
 */
@RunWith(SpringRunner.class)  //底层用junit  SpringJUnit4ClassRunner
@SpringBootTest(classes={FastjsonApplication.class})//启动整个springboot工程
public class FastJsonTest2 {

    @Test
    public void testJson(){
        String json="{\"name\":\"刘德华\",\"age\":35,\"some\":[{\"k1\":\"v1\",\"k2\":\"v2\"},{\"k3\":\"v3\",\"k4\":\"v4\"}]}";
        JSONObject jso=JSON.parseObject(json);//json字符串转换成jsonobject对象
        System.out.println("初始jsonObject:\n"+jso+"\n");//{"some":[{"k1":"v1","k2":"v2"},{"k3":"v3","k4":"v4"}],"name":"刘德华","age":35}

        JSONArray jsarr=jso.getJSONArray("some");//jsonobject对象取得some对应的jsonarray数组
        System.out.println("jsonObject里面的jsonarray:\n"+jsarr+"\n");//[{"k1":"v1","k2":"v2"},{"k3":"v3","k4":"v4"}]

        JSONObject ao=jsarr.getJSONObject(0);//jsonarray对象通过getjsonobjext(index)方法取得数组里面的jsonobject对象
        System.out.println("jsonObject里面的jsonarray里面的第一个jsonobject：\n"+ao+"\n");//{"k1":"v1","k2":"v2"}

        String vString=ao.getString("k1");//jsonobject对象通过key直接取得String的值
        System.out.println("jsonObject里面的jsonarray里面的第一个jsonobject里的键值对对k1取值：\n"+vString+"\n");//v1
    }

    /**
     * 测试modify
     */
    @Test
    public void testJson2(){
        String json="[{\n" +
                "\t\"deviceModel\": \"Dw\",\"alarmCodes\": \"code4,code5\"\n" +
                "},{\n" +
                "\t\"deviceModel\": \"ss\",\"alarmCodes\": \"code1,code2\"\n" +
                "}]";
        List<DeviceModelAlarmDto> deviceModelAlarmDtos = JSON.parseArray(json, DeviceModelAlarmDto.class);//json字符串转换成jsonobject对象
        System.out.println(JSON.toJSONString(deviceModelAlarmDtos,true));
    }

}
